# coding=utf-8
# 全世界最帅的帅哥
import json

from flask import jsonify, redirect, current_app, request
from flask_jwt_extended import verify_jwt_in_request, get_jwt_identity
from ysgg1_club_comment.constant.redis_prefix import RedisPrefix
from ysgg1_club_comment.redis_client import redis_client
from ysgg1_club_gateway.config.url_mappings import MICROSERVICE_URLS
from ysgg1_club_gateway.constant.url_constant import WHITE_URL_LIST
from ysgg1_club_gateway.utils.custom_rediret import redirect_with_headers


def proxy_request(service, remaining_path):
    if service not in MICROSERVICE_URLS:
        return jsonify({'error': 'Service not found'}), 404

    url = f"{MICROSERVICE_URLS[service]}/{service}/{remaining_path}"
    url_path = service + "/" + remaining_path
    # 白名单放行
    if url_path in WHITE_URL_LIST:
        current_app.logger.info(f"转发请求到{url}")
        return redirect(url)

    # 先确定登录 会自动抛出NoAuthorizationError的异常 高兴的话自己去写
    if verify_jwt_in_request():
        # 鉴权逻辑
        current_user = get_jwt_identity()
        if request.method == "GET":
            response = redirect_with_headers(url, current_user)
            return response

        key = RedisPrefix.AUTH_PERMISSION_PREFIX + "." + current_user
        permission_bytes_json = redis_client.get(key)
        permission_list = json.loads(permission_bytes_json.decode())
        method = request.method
        permission = service + ":" + method.lower()
        for permission_info in permission_list:
            if permission == permission_info["permission_key"]:
                current_app.logger.info(f"转发请求到{url}")
                return redirect(url)

        else:
            return {"code": 401, "message": "you don't have permission"}
